package commonutils;


import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 基础类型对象工具
 *
 * @author Sky
 */
public class ObjectUtils {


    public static boolean isNotBlank(Object data) {
        return !isBlank(data);
    }

    @SuppressWarnings("rawtypes")
    public static boolean isBlank(Object data) {
        if (null == data) {
            return true;
        }
        if (data instanceof String) {
            return StringUtils.isBlank(data.toString());
        } else if (data instanceof Collection) {
            Collection collection = (Collection) data;
            return collection.size() <= 0;
        } else if (data instanceof Map) {
            Map map = (Map) data;
            return map.size() <= 0;
        }
        if (data instanceof Integer) {
            int value = (Integer) data;
            return value == 0;
        } else if (data instanceof Long) {
            Long value = (Long) data;
            return value == 0;
        } else if (data instanceof Double) {
            Double value = (Double) data;
            return value == 0;
        } else if (data instanceof Float) {
            Float value = (Float) data;
            return value == 0;
        }
        return false;
    }



    public static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            String className= pd.getReadMethod().getReturnType().getName();
            if("java.lang.Long".equals(className) || "java.lang.long".equals(className)){
        		//null 也是空的
                if(null==srcValue){
                    emptyNames.add(pd.getName());
                }
                else if(null!=srcValue&&0L==(Long)srcValue){//如果是Long类型  值为0 视为null
        			emptyNames.add(pd.getName());
        		}
        	}
            else {
        	    	  if (srcValue == null) {
        	    		  emptyNames.add(pd.getName());  
        	    	  }
				}
          
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    public static void copyPropertiesIgnoreNull(Object desc, Object orig){
        BeanUtils.copyProperties(orig, desc, getNullPropertyNames(orig));
       
    }
    public static void copyProperties(Object desc, Object orig){
        BeanUtils.copyProperties(orig, desc);
       
    }

}
